package com.ljy.jymail.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ljy.common.to.es.SkuEsModal;
import com.ljy.common.utils.R;
import com.ljy.common.vo.AttrResponseVo;
import com.ljy.jymail.search.Constant.EsConstant;
import com.ljy.jymail.search.Feign.ProductFeignService;
import com.ljy.jymail.search.config.JymailElasticConfig;
import com.ljy.jymail.search.service.MailSearchService;
import com.ljy.jymail.search.vo.BrandVo;
import com.ljy.jymail.search.vo.SearchParam;
import com.ljy.jymail.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MailSearchServiceImpl implements MailSearchService {


    @Autowired
    private RestHighLevelClient client;


    @Autowired
    private ProductFeignService productFeignService;

    /*
     * param:检索传入的参数
     * searchResult:返回的所有信息
     *
     *
     * */
    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result = null;

        //动态构建出查询中需要的DSL语句
        //准备检索请求

        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            //执行检索请求
            SearchResponse search = client.search(searchRequest, JymailElasticConfig.COMMON_OPTIONS);
            //分析响应数据，封装成需要的格式
            result = buildSearchResult(search, param);


        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }


    /*
     * 构建查询结果数据
     *
     * */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        //TODO:1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModal> esModal = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModal skuEsModal = JSON.parseObject(sourceAsString, SkuEsModal.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {

                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highLight = skuTitle.getFragments()[0].string();

                    skuEsModal.setSkuTitle(highLight);
                }

                esModal.add(skuEsModal);
            }
        }
        result.setProduct(esModal);



        //TODO:2、当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();

        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1.得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            //2.得到属性名
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //3.得到属性值
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();

                return keyAsString;
            }).collect(Collectors.toList());


            attrVo.setAttrValue(attrValue);

            attrVos.add(attrVo);
        }


        result.setAttrs(attrVos);

        //TODO:3、当前商品涉及的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //1、得到品牌Id
            long brandId = bucket.getKeyAsNumber().longValue();
            //2、得到品牌名
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            //3、得到品牌图片信息
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }

        result.setBrands(brandVos);

        //TODO:4、当前商品涉及的所有分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类Id
            catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
            //得到分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            //catalogName信息
            String keyAsString = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(keyAsString);

            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //以上信息从聚合信息中获取

        //TODO:5、分页信息-页码
        result.setPageNum(param.getPageNum());
        //分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //分页信息-总页码
        /*
         * 总页码算法：
         *   总记录数 / 每页量 :   11 /2 = 5 .. 1
         *
         *
         *
         * */
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) (total / EsConstant.PRODUCT_PAGESIZE) + 1;
        result.setTotalPages(totalPages);
        //遍历总页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i < totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);


        //6、构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrsInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode = encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace =  param.get_queryString().replace("&attrs=" + encode, "");
//                replace =  param.get_queryString().replace("?attrs=" + encode, "?");

                navVo.setLink("http://search.jymail.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }


        //品牌，分类 - 面包屑
        if (param.getBrandId()!=null && param.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            //TODO:远程查询所有品牌
            R r = productFeignService.brandsInfo(param.getBrandId());
            if (r.getCode()==0){
                List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String brandNavs = "";
                for (BrandVo brandVo : brand) {
                    buffer.append(brandVo.getBrandName()+";");
                    String encode = null;

                    try {
                        encode = URLEncoder.encode(brandVo.getBrandId()+"","UTF-8");
                        encode = encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    brandNavs =  param.get_queryString().replace("&brandId=" + encode, "");
//                    brandNavs =  param.get_queryString().replace("?brandId=" + encode, "?");

                   }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.jymail.com/list.html?"+brandNavs);

            }
            navs.add(navVo);
        }

        return result;
    }

    private String replaceQueryString(SearchParam param, String attr,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(attr,"UTF-8");
            encode = encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&"+ key +"=" + encode, "");
    }


    /*
     * 准备检索请求
     *
     * 模糊匹配，过滤(属性，分类，品牌，价格区间，库存),排序，分页，高亮，聚合
     *
     * */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //构建dsl语句
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*
         * 模糊匹配，过滤(属性，分类，品牌，价格空间)
         *
         * */
        //bool
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //must
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        //filter:
        //三级分类Id查询
        if (param.getCatalog3id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3id()));
        }
        //品牌Id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //所有指定属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {

            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                //attr = 1_5寸:8寸
                //首先用_分割出id
                String[] s = attrStr.split("_");
                String attrId = s[0];
                //以：分割成多个检索的值
                String[] attrValue = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));
                //每一个属性都必须生成一个嵌入式的nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }

        //TODO:此处将默认查询没有库存的(没有库存的数据更多方便展示)
//        param.setHasStock(0);
        //库存查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1 ? true : false));
        }

        //价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            //1_500/_500/_500
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }

                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        //拼接所有查询条件
        builder.query(boolQuery);
        //TODO:2-分页，排序，高亮
        //2.1排序
        if (!StringUtils.isEmpty(param.getSort())) {
            //参数模板 sort_asc/desc
            String[] s = param.getSort().split("_");
            //被排序字段s[0]  排序方法s[1]
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0], order);
        }
        //2.2分页  计算 pageSize:5
        //  pageNum: 1 from :0 size:5 [0,1,2,3,4]
        //  pageNum: 2 from :5 size:5 [5,6,7,8,9]
        //  from=  (pageNum-1)*size
        builder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        builder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        //3聚合条件
        //TODO:3.1品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //3.1.1品牌聚合的子聚合 品牌名-图片地址
        TermsAggregationBuilder brandName = AggregationBuilders.terms("brand_name_agg").field("brandName").size(1);
        TermsAggregationBuilder brandImg = AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1);
        brandAgg.subAggregation(brandName);
        brandAgg.subAggregation(brandImg);
        builder.aggregation(brandAgg);

        //TODO:3.2分类聚合 catalogAGG
        TermsAggregationBuilder catalogId = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        //3.2.1子聚合 catalogName
        TermsAggregationBuilder catalogName = AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1);
        catalogId.subAggregation(catalogName);
        builder.aggregation(catalogId);


        //TODO:3.3属性聚合  -嵌入聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        //3.3.1 属性Id
        TermsAggregationBuilder attrId = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);

        //3.3.1.1 子聚合 - 属性名
        TermsAggregationBuilder attrName = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10);
        attrId.subAggregation(attrName);
        //3.3.1.2 子聚合 - 属性值
        TermsAggregationBuilder attrValue = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50);
        attrId.subAggregation(attrValue);
        //将子聚合都封装到大聚合中
        attrAgg.subAggregation(attrId);

        //封装属性聚合
        builder.aggregation(attrAgg);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);
        return searchRequest;
    }
}
